<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<span class="iconify" data-icon="mdi:medal" style="color: white;"></span>
				运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="flex items-center gap-6">
				<div class="flex items-center gap-2">
					<img id="img-head" src="img/jstu1.webp">
					<span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
				</div>
				<div class="flex items-center gap-2">
					<a href="javascript:void(0)" class="denglu" @click="handleLogout">退出登录</a>
				</div>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }">
				<span class="iconify" data-icon="mdi:view-dashboard"></span>
				<a @click="$router.push('/admin')">系统管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
				<span class="iconify" data-icon="mdi:account-group"></span>
				<a @click="$router.push('/admin/users')">用户管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/projects' }">
				<span class="iconify" data-icon="mdi:clipboard-list"></span>
				<a @click="$router.push('/admin/projects')">项目管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }">
				<span class="iconify" data-icon="mdi:calendar-clock"></span>
				<a @click="$router.push('/admin/schedule')">赛程管理</a>
			</div>
			<div class="menu-item active">
				<span class="iconify" data-icon="mdi:whistle"></span>
				裁判管理
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<!-- 面包屑导航 -->
			<el-breadcrumb class="breadcrumb" separator="/">
				<el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
				<el-breadcrumb-item>裁判管理</el-breadcrumb-item>
			</el-breadcrumb>

			<div class="main-content-header">
				<h1 class="text-2xl font-medium">裁判信息管理</h1>
				<div class="header-actions">
					<el-button type="success" size="small" @click="handleImport">
						<i class="el-icon-upload2"></i> 批量导入
					</el-button>
					<el-button type="info" size="small" @click="handleExport">
						<i class="el-icon-download"></i> 导出数据
					</el-button>
					<el-button type="primary" size="small" @click="handleAdd">
						<i class="el-icon-plus"></i> 添加裁判
					</el-button>
				</div>
			</div>

			<!-- 统计信息卡片 -->
			<div class="statistics-container">
				<el-row :gutter="20">
					<el-col :span="6">
						<div class="stat-card">
							<div class="stat-icon total">
								<i class="el-icon-user"></i>
							</div>
							<div class="stat-info">
								<div class="stat-title">裁判总数</div>
								<div class="stat-value">{{ statistics.totalReferees || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-card">
							<div class="stat-icon active">
								<i class="el-icon-check"></i>
							</div>
							<div class="stat-info">
								<div class="stat-title">激活裁判</div>
								<div class="stat-value">{{ statistics.activeReferees || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-card">
							<div class="stat-icon senior">
								<i class="el-icon-star-on"></i>
							</div>
							<div class="stat-info">
								<div class="stat-title">高级裁判</div>
								<div class="stat-value">{{ statistics.seniorReferees || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-card">
							<div class="stat-icon available">
								<i class="el-icon-time"></i>
							</div>
							<div class="stat-info">
								<div class="stat-title">当前可用</div>
								<div class="stat-value">{{ statistics.availableReferees || 0 }}</div>
							</div>
						</div>
					</el-col>
				</el-row>
			</div>

			<!-- 搜索区域 -->
			<div class="search-bar">
				<el-form :inline="true" :model="searchForm" size="small">
					<el-form-item label="姓名">
						<el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable style="width: 180px"></el-input>
					</el-form-item>
					<el-form-item label="工号">
						<el-input v-model="searchForm.employeeNumber" placeholder="请输入工号" clearable style="width: 180px"></el-input>
					</el-form-item>
					<el-form-item label="学院">
						<el-input v-model="searchForm.department" placeholder="请输入学院" clearable style="width: 180px"></el-input>
					</el-form-item>
					<el-form-item label="资质等级">
						<el-select v-model="searchForm.levelId" placeholder="请选择资质等级" clearable style="width: 150px">
							<el-option v-for="level in refereeLevels" :key="level.id" :label="level.name" :value="level.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="专长">
						<el-input v-model="searchForm.specialty" placeholder="请输入专长" clearable style="width: 180px"></el-input>
					</el-form-item>
					<el-form-item label="状态">
						<el-select v-model="searchForm.isActive" placeholder="请选择状态" clearable style="width: 120px">
							<el-option label="激活" :value="true"></el-option>
							<el-option label="停用" :value="false"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleSearch" :loading="loading">
							<i class="el-icon-search"></i> 搜索
						</el-button>
						<el-button @click="handleReset">
							<i class="el-icon-refresh"></i> 重置
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 裁判管理表格 -->
			<div class="table-container">
				<el-table
					:data="tableData"
					v-loading="loading"
					stripe
					border
					style="width: 100%"
					@selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center"></el-table-column>
					<el-table-column prop="id" label="裁判ID" width="80" align="center"></el-table-column>
					<el-table-column prop="employeeNumber" label="工号" width="120" align="center"></el-table-column>
					<el-table-column prop="realName" label="姓名" width="120" align="center"></el-table-column>
					<el-table-column prop="gender" label="性别" width="80" align="center">
						<template #default="scope">
							{{ scope.row.gender === '男' ? '男' : scope.row.gender === '女' ? '女' : '-' }}
						</template>
					</el-table-column>
					<el-table-column prop="department" label="学院/部门" width="150" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="phone" label="联系电话" width="130" align="center"></el-table-column>
					<el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip></el-table-column>
					<el-table-column prop="levelName" label="资质等级" width="120" align="center">
						<template #default="scope">
							<el-tag :type="getLevelTagType(scope.row.levelName)" size="small">
								{{ scope.row.levelName || '-' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="specialty" label="专长" width="120" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="isActive" label="状态" width="80" align="center">
						<template #default="scope">
							<el-tag :type="scope.row.isActive ? 'success' : 'danger'" size="small">
								{{ scope.row.isActive ? '激活' : '停用' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="assignmentCount" label="分配项目数" width="100" align="center">
						<template #default="scope">
							<span>{{ scope.row.assignmentCount || 0 }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="createdAt" label="创建时间" width="180" align="center">
						<template #default="scope">
							{{ formatDateTime(scope.row.createdAt) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" width="320" align="center" fixed="right">
						<template #default="scope">
							<el-button-group size="mini">
								<el-button type="primary" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
								<el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
								<el-button
									:type="scope.row.isActive ? 'warning' : 'success'"
									@click="handleToggleStatus(scope.row)">
									{{ scope.row.isActive ? '停用' : '激活' }}
								</el-button>
								<el-button type="info" icon="el-icon-star-on" @click="handleUpdateLevel(scope.row)">资质</el-button>
								<el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
							</el-button-group>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页控制 -->
				<div class="pagination-container">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pagination.currentPage"
						:page-sizes="[10, 20, 50, 100]"
						:page-size="pagination.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="pagination.total">
					</el-pagination>
				</div>

				<!-- 批量操作 -->
				<div class="batch-operations" v-if="selectedReferees.length > 0">
					<span>已选择 {{ selectedReferees.length }} 项</span>
					<el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
					<el-button type="warning" size="small" @click="handleBatchDeactivate">批量停用</el-button>
					<el-button type="success" size="small" @click="handleBatchActivate">批量激活</el-button>
					<el-button type="info" size="small" @click="handleBatchExport">批量导出</el-button>
				</div>
			</div>

			<!-- 裁判编辑对话框 -->
			<el-dialog
				:title="dialogTitle"
				v-model="dialogVisible"
				width="700px"
				:before-close="handleDialogClose">
				<el-form :model="refereeForm" :rules="refereeFormRules" ref="refereeFormRef" label-width="100px">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="工号" prop="employeeNumber">
								<el-input v-model="refereeForm.employeeNumber" :disabled="isEdit" placeholder="请输入工号"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="姓名" prop="realName">
								<el-input v-model="refereeForm.realName" placeholder="请输入真实姓名"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="性别" prop="gender">
								<el-select v-model="refereeForm.gender" placeholder="请选择性别" style="width: 100%">
									<el-option label="男" value="男"></el-option>
									<el-option label="女" value="女"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="学院/部门" prop="department">
								<el-input v-model="refereeForm.department" placeholder="请输入学院或部门"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="联系电话" prop="phone">
								<el-input v-model="refereeForm.phone" placeholder="请输入联系电话"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="邮箱" prop="email">
								<el-input v-model="refereeForm.email" placeholder="请输入邮箱"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="资质等级" prop="levelId">
								<el-select v-model="refereeForm.levelId" placeholder="请选择资质等级" style="width: 100%">
									<el-option v-for="level in refereeLevels" :key="level.id" :label="level.name" :value="level.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="证书编号" prop="certificateNumber">
								<el-input v-model="refereeForm.certificateNumber" placeholder="请输入证书编号"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="专长项目" prop="specialty">
								<el-input v-model="refereeForm.specialty" placeholder="请输入专长项目，多个项目用逗号分隔"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="备注信息" prop="remarks">
								<el-input
									v-model="refereeForm.remarks"
									type="textarea"
									:rows="3"
									placeholder="请输入备注信息">
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="状态" prop="isActive">
								<el-switch
									v-model="refereeForm.isActive"
									active-text="激活"
									inactive-text="停用">
								</el-switch>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleDialogClose">取消</el-button>
						<el-button type="primary" @click="handleSave" :loading="saveLoading">确定</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 裁判详情对话框 -->
			<el-dialog
				title="裁判详情"
				v-model="detailDialogVisible"
				width="800px">
				<div v-if="currentReferee" class="referee-detail">
					<el-row :gutter="20">
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">工号：</span>
								<span class="value">{{ currentReferee.employeeNumber }}</span>
							</div>
						</el-col>
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">姓名：</span>
								<span class="value">{{ currentReferee.realName }}</span>
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">性别：</span>
								<span class="value">{{ currentReferee.gender }}</span>
							</div>
						</el-col>
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">学院/部门：</span>
								<span class="value">{{ currentReferee.department }}</span>
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">联系电话：</span>
								<span class="value">{{ currentReferee.phone }}</span>
							</div>
						</el-col>
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">邮箱：</span>
								<span class="value">{{ currentReferee.email }}</span>
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">资质等级：</span>
								<el-tag :type="getLevelTagType(currentReferee.levelName)" size="small">
									{{ currentReferee.levelName || '-' }}
								</el-tag>
							</div>
						</el-col>
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">证书编号：</span>
								<span class="value">{{ currentReferee.certificateNumber || '-' }}</span>
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">专长项目：</span>
								<span class="value">{{ currentReferee.specialty || '-' }}</span>
							</div>
						</el-col>
						<el-col :span="12">
							<div class="detail-item">
								<span class="label">状态：</span>
								<el-tag :type="currentReferee.isActive ? 'success' : 'danger'" size="small">
									{{ currentReferee.isActive ? '激活' : '停用' }}
								</el-tag>
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="20" v-if="currentReferee.remarks">
						<el-col :span="24">
							<div class="detail-item">
								<span class="label">备注信息：</span>
								<span class="value">{{ currentReferee.remarks }}</span>
							</div>
						</el-col>
					</el-row>
					<el-divider>执裁记录</el-divider>
					<div class="records-container">
						<el-table :data="refereeRecords" border style="width: 100%">
							<el-table-column prop="projectName" label="项目名称" width="150"></el-table-column>
							<el-table-column prop="eventDate" label="比赛日期" width="120">
								<template #default="scope">
									{{ formatDate(scope.row.eventDate) }}
								</template>
							</el-table-column>
							<el-table-column prop="location" label="比赛地点" width="120"></el-table-column>
							<el-table-column prop="role" label="执裁角色" width="100">
								<template #default="scope">
									<el-tag size="small">{{ scope.row.role }}</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="rating" label="评分" width="80">
								<template #default="scope">
									<el-rate
										v-model="scope.row.rating"
										disabled
										text-color="#ff9900"
										show-score>
									</el-rate>
								</template>
							</el-table-column>
							<el-table-column prop="status" label="状态" width="100">
								<template #default="scope">
									<el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'" size="small">
										{{ scope.row.status }}
									</el-tag>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</el-dialog>

			<!-- 资质等级更新对话框 -->
			<el-dialog
				title="更新资质等级"
				v-model="levelDialogVisible"
				width="500px">
				<el-form :model="levelForm" :rules="levelFormRules" ref="levelFormRef" label-width="100px">
					<el-form-item label="裁判姓名">
						<el-input v-model="levelForm.refereeName" disabled></el-input>
					</el-form-item>
					<el-form-item label="资质等级" prop="levelId">
						<el-select v-model="levelForm.levelId" placeholder="请选择资质等级" style="width: 100%">
							<el-option v-for="level in refereeLevels" :key="level.id" :label="level.name" :value="level.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="证书编号" prop="certificateNumber">
						<el-input v-model="levelForm.certificateNumber" placeholder="请输入证书编号"></el-input>
					</el-form-item>
					<el-form-item label="发证机构" prop="issuingOrganization">
						<el-input v-model="levelForm.issuingOrganization" placeholder="请输入发证机构"></el-input>
					</el-form-item>
					<el-form-item label="证书有效期" prop="certificateExpiry">
						<el-date-picker
							v-model="levelForm.certificateExpiry"
							type="date"
							placeholder="选择证书有效期"
							style="width: 100%">
						</el-date-picker>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="levelDialogVisible = false">取消</el-button>
						<el-button type="primary" @click="handleSaveLevel" :loading="saveLoading">确定</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 导入裁判对话框 -->
			<el-dialog
				title="批量导入裁判"
				v-model="importDialogVisible"
				width="500px">
				<el-upload
					class="upload-demo"
					ref="upload"
					action=""
					:auto-upload="false"
					:limit="1"
					accept=".xlsx,.xls"
					:on-change="handleFileChange">
					<template #trigger>
						<el-button size="small" type="primary">选取文件</el-button>
					</template>
					<template #tip>
						<div class="el-upload__tip">只能上传xlsx/xls文件，且不超过5MB</div>
					</template>
				</el-upload>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="importDialogVisible = false">取消</el-button>
						<el-button type="primary" @click="handleUpload" :loading="uploadLoading">确定上传</el-button>
					</div>
				</template>
			</el-dialog>
		</main>
	</div>
</template>

<script>
import {
	getRefereePage,
	getRefereeById,
	addReferee,
	updateReferee,
	deleteReferee,
	batchDeleteReferees,
	updateRefereeStatus,
	getRefereeLevels,
	updateRefereeLevel,
	getRefereeStatistics,
	getRefereeRecords,
	importReferees,
	exportReferees
} from '@/api/referee'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'RefereeManagement',
  setup() {
    const authStore = useAuthStore()
    return {
      authStore
    }
  },
	data() {
		return {
			// 当前用户信息
			currentUser: null,

			// 搜索表单
			searchForm: {
				realName: '',
				employeeNumber: '',
				department: '',
				levelId: null,
				specialty: '',
				isActive: null
			},

			// 裁判资质等级列表
			refereeLevels: [],

			// 统计信息
			statistics: {
				totalReferees: 0,
				activeReferees: 0,
				seniorReferees: 0,
				availableReferees: 0
			},

			// 表格数据
			tableData: [],
			loading: false,

			// 分页信息
			pagination: {
				currentPage: 1,
				pageSize: 10,
				total: 0
			},

			// 选中的裁判
			selectedReferees: [],

			// 对话框相关
			dialogVisible: false,
			dialogTitle: '添加裁判',
			isEdit: false,
			saveLoading: false,

			// 裁判表单
			refereeForm: {
				id: null,
				employeeNumber: '',
				realName: '',
				gender: '',
				department: '',
				phone: '',
				email: '',
				levelId: null,
				certificateNumber: '',
				specialty: '',
				remarks: '',
				isActive: true
			},

			// 表单验证规则
			refereeFormRules: {
				employeeNumber: [
					{ required: true, message: '请输入工号', trigger: 'blur' },
					{ min: 3, max: 20, message: '工号长度在 3 到 20 个字符', trigger: 'blur' }
				],
				realName: [
					{ required: true, message: '请输入真实姓名', trigger: 'blur' },
					{ min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
				],
				gender: [
					{ required: true, message: '请选择性别', trigger: 'change' }
				],
				department: [
					{ required: true, message: '请输入学院或部门', trigger: 'blur' }
				],
				phone: [
					{ required: true, message: '请输入联系电话', trigger: 'blur' },
					{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
				],
				email: [
					{ required: true, message: '请输入邮箱', trigger: 'blur' },
					{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
				],
				levelId: [
					{ required: true, message: '请选择资质等级', trigger: 'change' }
				]
			},

			// 详情对话框
			detailDialogVisible: false,
			currentReferee: null,
			refereeRecords: [],

			// 资质等级对话框
			levelDialogVisible: false,
			levelForm: {
				refereeId: null,
				refereeName: '',
				levelId: null,
				certificateNumber: '',
				issuingOrganization: '',
				certificateExpiry: null
			},
			levelFormRules: {
				levelId: [
					{ required: true, message: '请选择资质等级', trigger: 'change' }
				],
				certificateNumber: [
					{ required: true, message: '请输入证书编号', trigger: 'blur' }
				],
				issuingOrganization: [
					{ required: true, message: '请输入发证机构', trigger: 'blur' }
				],
				certificateExpiry: [
					{ required: true, message: '请选择证书有效期', trigger: 'change' }
				]
			},

			// 导入对话框
			importDialogVisible: false,
			uploadFile: null,
			uploadLoading: false
		}
	},

	created() {
		// 获取当前用户信息
		this.currentUser = this.authStore.userInfo || JSON.parse(localStorage.getItem('user'))
		// 初始化数据
		this.initData()
	},

	methods: {
		// 初始化数据
		async initData() {
			await this.loadRefereeLevels()
			await this.loadStatistics()
			this.loadData()
		},

		// 加载数据
		async loadData() {
			this.loading = true
			try {
				const params = {
					...this.searchForm,
					currentPage: this.pagination.currentPage,
					pageSize: this.pagination.pageSize
				}

				const response = await getRefereePage(this.pagination.currentPage, this.pagination.pageSize, params)

				if (response.code === 200) {
					this.tableData = response.data.records
					this.pagination.total = response.data.total
				} else {
					this.$message.error(response.message || '获取数据失败')
				}
			} catch (error) {
				console.error('获取裁判数据失败:', error)
				this.$message.error('获取数据失败')
			} finally {
				this.loading = false
			}
		},

		// 加载裁判资质等级
		async loadRefereeLevels() {
			try {
				const response = await getRefereeLevels()
				if (response.code === 200) {
					this.refereeLevels = response.data
				}
			} catch (error) {
				console.error('获取裁判资质等级失败:', error)
			}
		},

		// 加载统计信息
		async loadStatistics() {
			try {
				const response = await getRefereeStatistics()
				if (response.code === 200) {
					this.statistics = response.data
				}
			} catch (error) {
				console.error('获取统计信息失败:', error)
			}
		},

		// 搜索
		handleSearch() {
			this.pagination.currentPage = 1
			this.loadData()
		},

		// 重置搜索
		handleReset() {
			this.searchForm = {
				realName: '',
				employeeNumber: '',
				department: '',
				levelId: null,
				specialty: '',
				isActive: null
			}
			this.handleSearch()
		},

		// 分页大小改变
		handleSizeChange(val) {
			this.pagination.pageSize = val
			this.loadData()
		},

		// 当前页改变
		handleCurrentChange(val) {
			this.pagination.currentPage = val
			this.loadData()
		},

		// 表格选择改变
		handleSelectionChange(selection) {
			this.selectedReferees = selection
		},

		// 添加裁判
		handleAdd() {
			this.dialogTitle = '添加裁判'
			this.isEdit = false
			this.refereeForm = {
				id: null,
				employeeNumber: '',
				realName: '',
				gender: '',
				department: '',
				phone: '',
				email: '',
				levelId: null,
				certificateNumber: '',
				specialty: '',
				remarks: '',
				isActive: true
			}
			this.dialogVisible = true
		},

		// 编辑裁判
		async handleEdit(row) {
			this.dialogTitle = '编辑裁判'
			this.isEdit = true

			try {
				const response = await getRefereeById(row.id)
				if (response.code === 200) {
					this.refereeForm = {
						...response.data
					}
					this.dialogVisible = true
				} else {
					this.$message.error(response.message || '获取裁判信息失败')
				}
			} catch (error) {
				console.error('获取裁判信息失败:', error)
				this.$message.error('获取裁判信息失败')
			}
		},

		// 查看裁判详情
		async handleView(row) {
			try {
				const response = await getRefereeById(row.id)
				if (response.code === 200) {
					this.currentReferee = response.data
					this.detailDialogVisible = true
					// 加载执裁记录
					this.loadRefereeRecords(row.id)
				} else {
					this.$message.error(response.message || '获取裁判信息失败')
				}
			} catch (error) {
				console.error('获取裁判信息失败:', error)
				this.$message.error('获取裁判信息失败')
			}
		},

		// 加载裁判执裁记录
		async loadRefereeRecords(refereeId) {
			try {
				const response = await getRefereeRecords(refereeId, {})
				if (response.code === 200) {
					this.refereeRecords = response.data.records || []
				}
			} catch (error) {
				console.error('获取执裁记录失败:', error)
			}
		},

		// 保存裁判
		async handleSave() {
			this.$refs.refereeFormRef.validate(async (valid) => {
				if (valid) {
					this.saveLoading = true
					try {
						let response
						if (this.isEdit) {
							response = await updateReferee(this.refereeForm)
						} else {
							response = await addReferee(this.refereeForm)
						}

						if (response.code === 200) {
							this.$message.success(this.isEdit ? '更新成功' : '添加成功')
							this.dialogVisible = false
							this.loadData()
							this.loadStatistics()
						} else {
							this.$message.error(response.message || (this.isEdit ? '更新失败' : '添加失败'))
						}
					} catch (error) {
						console.error('保存裁判失败:', error)
						this.$message.error(this.isEdit ? '更新失败' : '添加失败')
					} finally {
						this.saveLoading = false
					}
				}
			})
		},

		// 删除裁判
		handleDelete(row) {
			this.$confirm('确定要删除该裁判吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const response = await deleteReferee(row.id)
					if (response.code === 200) {
						this.$message.success('删除成功')
						this.loadData()
						this.loadStatistics()
					} else {
						this.$message.error(response.message || '删除失败')
					}
				} catch (error) {
					console.error('删除裁判失败:', error)
					this.$message.error('删除失败')
				}
			})
		},

		// 批量删除
		handleBatchDelete() {
			this.$confirm(`确定要删除选中的 ${this.selectedReferees.length} 个裁判吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const refereeIds = this.selectedReferees.map(referee => referee.id)
					const response = await batchDeleteReferees(refereeIds)
					if (response.code === 200) {
						this.$message.success('批量删除成功')
						this.loadData()
						this.loadStatistics()
						this.selectedReferees = []
					} else {
						this.$message.error(response.message || '批量删除失败')
					}
				} catch (error) {
					console.error('批量删除失败:', error)
					this.$message.error('批量删除失败')
				}
			})
		},

		// 切换裁判状态
		async handleToggleStatus(row) {
			const action = row.isActive ? '停用' : '激活'
			this.$confirm(`确定要${action}该裁判吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const response = await updateRefereeStatus(row.id, !row.isActive)
					if (response.code === 200) {
						this.$message.success(`${action}成功`)
						this.loadData()
						this.loadStatistics()
					} else {
						this.$message.error(response.message || `${action}失败`)
					}
				} catch (error) {
					console.error(`${action}裁判失败:`, error)
					this.$message.error(`${action}失败`)
				}
			})
		},

		// 批量激活
		handleBatchActivate() {
			this.$confirm(`确定要激活选中的 ${this.selectedReferees.length} 个裁判吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const refereeIds = this.selectedReferees.map(referee => referee.id)
					const promises = refereeIds.map(id => updateRefereeStatus(id, true))
					await Promise.all(promises)
					this.$message.success('批量激活成功')
					this.loadData()
					this.loadStatistics()
					this.selectedReferees = []
				} catch (error) {
					console.error('批量激活失败:', error)
					this.$message.error('批量激活失败')
				}
			})
		},

		// 批量停用
		handleBatchDeactivate() {
			this.$confirm(`确定要停用选中的 ${this.selectedReferees.length} 个裁判吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const refereeIds = this.selectedReferees.map(referee => referee.id)
					const promises = refereeIds.map(id => updateRefereeStatus(id, false))
					await Promise.all(promises)
					this.$message.success('批量停用成功')
					this.loadData()
					this.loadStatistics()
					this.selectedReferees = []
				} catch (error) {
					console.error('批量停用失败:', error)
					this.$message.error('批量停用失败')
				}
			})
		},

		// 更新资质等级
		handleUpdateLevel(row) {
			this.levelForm = {
				refereeId: row.id,
				refereeName: row.realName,
				levelId: row.levelId,
				certificateNumber: row.certificateNumber || '',
				issuingOrganization: '',
				certificateExpiry: null
			}
			this.levelDialogVisible = true
		},

		// 保存资质等级
		async handleSaveLevel() {
			this.$refs.levelFormRef.validate(async (valid) => {
				if (valid) {
					this.saveLoading = true
					try {
						const certificateData = {
							certificateNumber: this.levelForm.certificateNumber,
							issuingOrganization: this.levelForm.issuingOrganization,
							certificateExpiry: this.levelForm.certificateExpiry
						}
						const response = await updateRefereeLevel(
							this.levelForm.refereeId,
							this.levelForm.levelId,
							certificateData
						)
						if (response.code === 200) {
							this.$message.success('资质等级更新成功')
							this.levelDialogVisible = false
							this.loadData()
						} else {
							this.$message.error(response.message || '资质等级更新失败')
						}
					} catch (error) {
						console.error('更新资质等级失败:', error)
						this.$message.error('资质等级更新失败')
					} finally {
						this.saveLoading = false
					}
				}
			})
		},

		// 导入裁判
		handleImport() {
			this.importDialogVisible = true
			this.uploadFile = null
		},

		// 文件选择改变
		handleFileChange(file) {
			this.uploadFile = file.raw
		},

		// 上传文件
		async handleUpload() {
			if (!this.uploadFile) {
				this.$message.warning('请选择要导入的文件')
				return
			}

			this.uploadLoading = true
			try {
				const response = await importReferees(this.uploadFile)
				if (response.code === 200) {
					this.$message.success('导入成功')
					this.importDialogVisible = false
					this.loadData()
					this.loadStatistics()
				} else {
					this.$message.error(response.message || '导入失败')
				}
			} catch (error) {
				console.error('导入失败:', error)
				this.$message.error('导入失败')
			} finally {
				this.uploadLoading = false
			}
		},

		// 导出数据
		async handleExport() {
			try {
				const response = await exportReferees(this.searchForm)
				// 创建下载链接
				const blob = new Blob([response.data])
				const url = window.URL.createObjectURL(blob)
				const link = document.createElement('a')
				link.href = url
				link.download = `裁判数据_${new Date().getTime()}.xlsx`
				link.click()
				window.URL.revokeObjectURL(url)
				this.$message.success('导出成功')
			} catch (error) {
				console.error('导出失败:', error)
				this.$message.error('导出失败')
			}
		},

		// 批量导出
		async handleBatchExport() {
			const refereeIds = this.selectedReferees.map(referee => referee.id)
			try {
				const response = await exportReferees({ refereeIds })
				// 创建下载链接
				const blob = new Blob([response.data])
				const url = window.URL.createObjectURL(blob)
				const link = document.createElement('a')
				link.href = url
				link.download = `选中裁判数据_${new Date().getTime()}.xlsx`
				link.click()
				window.URL.revokeObjectURL(url)
				this.$message.success('批量导出成功')
			} catch (error) {
				console.error('批量导出失败:', error)
				this.$message.error('批量导出失败')
			}
		},

		// 关闭对话框
		handleDialogClose() {
			this.dialogVisible = false
			this.$refs.refereeFormRef.resetFields()
		},

		// 退出登录
		handleLogout() {
			this.$confirm('确定要退出登录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				// 使用Pinia的logout方法
				this.authStore.logout()
				// 跳转到登录页
				this.$router.push('/login')
			})
		},

		// 获取资质等级标签类型
		getLevelTagType(levelName) {
			const typeMap = {
				'国家级': 'danger',
				'省级': 'warning',
				'市级': 'primary',
				'校级': 'success',
				'实习': 'info'
			}
			return typeMap[levelName] || 'primary'
		},

		// 格式化日期时间
		formatDateTime(dateTime) {
			if (!dateTime) return '-'
			return new Date(dateTime).toLocaleString('zh-CN')
		},

		// 格式化日期
		formatDate(date) {
			if (!date) return '-'
			return new Date(date).toLocaleDateString('zh-CN')
		}
	}
}
</script>

<style scoped>
/* 基础样式 */
* {
	font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
	background-color: #f0f2f5;
	color: #1a1a1a;
	margin: 0;
}

/* 容器布局 */
.app-container {
	max-width: 1440px;
	margin: 0 auto;
	display: grid;
	grid-template-columns: 240px 1fr;
	grid-template-rows: 64px 1fr;
	min-height: 100vh;
	background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
	grid-column: 1 / -1;
	background-color: #2C5AA0;
	display: flex;
	align-items: center;
	padding: 0 24px;
}

.logo {
	font-size: 18px;
	font-weight: bold;
	color: white;
	display: flex;
	align-items: center;
	gap: 8px;
}

.flex-grow {
	flex-grow: 1;
}

.flex {
	display: flex;
}

.items-center {
	align-items: center;
}

.gap-6 {
	gap: 24px;
}

.gap-2 {
	gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
	background-color: white;
	padding: 16px 0;
	border-right: 1px solid #e4e7ed;
}

.menu-item {
	padding: 12px 24px;
	color: #555;
	display: flex;
	align-items: center;
	gap: 12px;
	transition: all 0.3s;
	cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
	background-color: #e8eff9;
	color: #2C5AA0;
	border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
	padding: 24px;
	display: grid;
	grid-template-rows: auto auto 1fr;
	gap: 24px;
	overflow-y: auto;
}

/* 面包屑 */
.breadcrumb {
	margin-bottom: 16px;
}

.main-content-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 16px;
	border-bottom: 1px solid #e4e7ed;
}

.header-actions {
	display: flex;
	gap: 12px;
}

/* 统计卡片 */
.statistics-container {
	margin-bottom: 24px;
}

.stat-card {
	background: white;
	border-radius: 12px;
	padding: 24px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	display: flex;
	align-items: center;
	gap: 20px;
	transition: all 0.3s;
	cursor: pointer;
	height: 100%;
}

.stat-card:hover {
	transform: translateY(-5px);
	box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-icon {
	width: 70px;
	height: 70px;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28px;
	color: white;
	flex-shrink: 0;
}

.stat-icon.total {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
	background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.senior {
	background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.available {
	background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
	flex: 1;
}

.stat-title {
	font-size: 15px;
	color: #606266;
	margin-bottom: 8px;
	font-weight: 500;
}

.stat-value {
	font-size: 32px;
	font-weight: bold;
	color: #303133;
	line-height: 1;
}

/* 搜索区域 */
.search-bar {
	background: white;
	padding: 24px;
	border-radius: 12px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	margin-bottom: 24px;
}

/* 表格容器 */
.table-container {
	background: white;
	border-radius: 12px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	padding: 24px;
	overflow: hidden;
}

/* 分页容器 */
.pagination-container {
	margin-top: 20px;
	text-align: right;
}

/* 批量操作 */
.batch-operations {
	margin-top: 16px;
	padding: 16px;
	background-color: #f5f7fa;
	border-radius: 8px;
	display: flex;
	align-items: center;
	gap: 12px;
	border-left: 4px solid #409EFF;
}

.batch-operations span {
	font-weight: 500;
	color: #606266;
	margin-right: 8px;
}

/* 裁判详情样式 */
.referee-detail {
	padding: 20px;
}

.detail-item {
	display: flex;
	margin-bottom: 16px;
	align-items: center;
}

.detail-item .label {
	width: 100px;
	font-weight: 500;
	color: #606266;
}

.detail-item .value {
	flex: 1;
	color: #303133;
}

.records-container {
	margin-top: 20px;
}

/* 头像和退出登录 */
#img-head {
	height: 40px;
	width: 40px;
	border-radius: 50px;
}

.denglu {
	color: white;
	font-size: 15px;
	text-decoration: none;
}

.denglu:hover {
	color: #F44346;
}

.text-sm {
	font-size: 14px;
}

.text-white {
	color: white;
}

/* Element UI 样式调整 */
.el-table {
	margin-top: 16px;
}

.el-table th {
	background-color: #fafafa !important;
}

.el-form-item {
	margin-bottom: 0;
}

.el-upload {
	text-align: center;
}

.el-upload__tip {
	color: #606266;
	font-size: 12px;
	margin-top: 8px;
}

.el-divider {
	margin: 20px 0;
}

</style>